<?php

declare(strict_types=1);

namespace app\model;

use app\eslib\EsUtils;
use app\eslib\HttpUtils;

/**
 * 手机模型类
 * 功能：发送短信，话费充值
 */
class MobilesModel
{
    // 短信配置 (app_vendor.sms)
    protected $smsConfig = [
        // 聚合短信
        'key' => 'f79f4e9e6344993e76ca1b669bf20ac4',
        'tpl_id' => '215774',
        'tpl_last' => '蝶塔数据',

    ];

    // 手机充值配置 (app_vendor.mobile_recharge)
    protected $rechargeConfig = [
        // 聚合接口
        'key' => 'fc8a3a7f55af1cceaea9a4a72fb950f5',
    ];

    /**
     * 发送短信
     */
    public function sendSms($mobile, $code)
    {
        $url = "http://v.juhe.cn/sms/send";
        if (empty($this->smsConfig['key'])) {
            return EsUtils::stdMessage(false, '短信接口配置错误：Key 配置项无效！');
        }
        $params = array(
            'key'   => $this->smsConfig['key'], //您申请的APPKEY
            'mobile'    => $mobile, //接受短信的用户手机号码
            'tpl_id'    => $this->smsConfig['tpl_id'], //您申请的短信模板ID，根据实际情况修改
            'tpl_value' => '#code#=' . $code . '&#company#=' . $this->smsConfig['tpl_last'] //您设置的模板变量，根据实际情况修改
        );

        $paramstring = http_build_query($params);
        $msgInfo = HttpUtils::sendRequest($url, $paramstring);
        if (!$msgInfo['success']) {
            return EsUtils::stdMessage(false, '短信接口请求错误：' . $msgInfo['msg']);
        }
        $msgInfo = json_decode($msgInfo['data'], true); // array ('reason'=>'error key','result'=>NULL,'error_code'=>10001,)
        if ($msgInfo) {
            if ($msgInfo['error_code']) {
                return EsUtils::stdMessage(false, '短信接口错误：' . $msgInfo['reason']);
            }
            return EsUtils::stdMessage(true, '发送成功');
        } else {
            return EsUtils::stdMessage(false, '短信接口异常！请检查短信接口配置！');
        }
    }

    /**
     * 检测手机号码及金额是否能充值
     * @param string $mobile 手机号
     * @param int $money 充值金额,目前可选：1、2、5、10、20、30、50、100、200、300、500
     * @return 
     */
    public static function rechargeCheckByTJRH($mobile, $money)
    {
        $allowMoneys = [1, 2, 5, 10, 20, 30, 50, 100, 200, 300, 500];
        if (!in_array($money, $allowMoneys)) {
            return EsUtils::stdMessage(false, '充值金额无效，只能选：1、2、5、10、20、30、50、100、200、300、500');
        }
        $apiKey = '240afa20659c695cc10c6ce66536ae20';
        $apiUrl = "http://op.tianjurenhe.com/ofpay/mobile/telcheck?cardnum={$money}&phoneno={$mobile}&key={$apiKey}";
        // 返回参数说明：error_code?int:返回码; reason?string:返回说明; result?string:返回结果集
        $result = HttpUtils::get($apiUrl);
        $apiResult = json_decode($result['data'], true);
        return EsUtils::stdMessage($apiResult['error_code'] == 0 ? 1 : 0, $apiResult['reason'], $apiResult['result']);
    }

    /**
     * 手机直充接口
     */
    public static function rechargeByTJRH($mobile, $money, $orderId)
    {
        $allowMoneys = [1, 2, 5, 10, 20, 30, 50, 100, 200, 300, 500];
        if (!in_array($money, $allowMoneys)) {
            return EsUtils::stdMessage(false, '充值金额无效，只能选：1、2、5、10、20、30、50、100、200、300、500');
        }
        $openId = 'JH3dd1466b307a362b3228f3581e7b3107';
        $apiKey = '240afa20659c695cc10c6ce66536ae20';
        // sign校验值，md5( OpenID+key+phoneno+cardnum+orderid)，OpenID在个人中心查询
        $sign = md5($openId . $apiKey . $mobile . $money . $orderId);
        $apiUrl = "http://op.tianjurenhe.com/ofpay/mobile/onlineorder?key={$apiKey}&phoneno={$mobile}&cardnum={$money}&orderid={$orderId}&sign={$sign}";
        // 返回参数说明：error_code?int:返回码; reason?string:返回说明; result?string:返回结果集
        // 返回示例：
        /**
         * {
         * "reason": "订单提交成功，等待充值",
         * "result": {
         *     "cardid": "1900212", // 充值的卡类ID
         *     "cardnum": "1", // 数量
         *     "ordercash": 49.25, // 进货价格
         *     "cardname": "江苏电信话费50元直充", // 充值名称
         *     "sporder_id": "20141120174602882", // 天聚人合订单号
         *     "uorderid":"2014123115121", // 商户自定的订单号
         *     "game_userid": "18913515122", // 充值的手机号码
         *     "game_state": "0" // 充值状态:0充值中 1成功 9撤销，刚提交都返回0
         * },
         * "error_code": 0
         * }
         */
        $result = HttpUtils::get($apiUrl);
        $apiResult = json_decode($result['data'], true);
        return EsUtils::stdMessage($apiResult['error_code'] == 0 ? 1 : 0, $apiResult['reason'], $apiResult['result']);
    }
    /**
     * 话费充值
     */
    public function rechargeCharge($mobile, $value, $provider = 'juhe')
    {
        $url = "http://op.juhe.cn/ofpay/mobile/telcheck";
        if (!isset($this->rechargeConfig['key'])) {
            return EsUtils::stdMessage(false, '充值接口配置错误：Key 配置项无效！');
        }
        $params = array(
            'key'   => $this->rechargeConfig['key'], //您申请的APPKEY
            'phoneno'    => $mobile, // 手机号码
            'cardnum'    => $value, // 充值金额,目前可选：1、2、5、10、20、30、50、100、200、300、500
        );

        $paramstring = http_build_query($params);
        $msgInfo = HttpUtils::sendRequest($url, $paramstring);
        if (!$msgInfo['success']) {
            return EsUtils::stdMessage(false, '充值接口请求错误：' . $msgInfo['msg']);
        }
        $msgInfo = json_decode($msgInfo['data'], true); // array ('reason'=>'error key','result'=>NULL,'error_code'=>10001,)
        if ($msgInfo) {
            if ($msgInfo['error_code']) {
                return EsUtils::stdMessage(false, '充值接口错误：' . $msgInfo['reason']);
            }
            return EsUtils::stdMessage(true, '充值成功');
        } else {
            return EsUtils::stdMessage(false, '充值接口异常！请检查充值接口配置！');
        }
    }

    /**
     * 检测手机号运营商
     */
    public static function getISPName($mobile)
    {
        if (!$mobile || strlen($mobile) < 11) {
            return false;
        }
        $start3 = substr($mobile, 0, 3);
        $haoduan = [
            '134,135,136,137,138,139,147,148,150,151,152,157,158,159,172,178,182,183,184,187,188,195,198' => '中国移动',
            '130,131,132,140,145,146,155,156,166,167,175,176,185,186' => '中国联通',
            '133,149,153,173,174,177,180,181,189,191,199' => '中国电信',
            '162,165,170,171' => '虚拟运营商',
        ];
        foreach ($haoduan as $nums => $name) {
            if (false !== strpos($nums, $start3)) {
                return $name;
            }
        }
        return $start3;
    }

    /**
     * 验证上发短信内容发送短信
     */
    public static function postedSendSms($mobile)
    {
        $accountSid = '8aaf0708773733a801775c8e42b70e81';
        $key = '4bd00cffcab74f2585e958b9441ce35c';
        $time = date("YmdHis");
        $sig = md5($accountSid . $key . $time);
        $base64 = base64_encode($accountSid . ':' . $time);
        $SigParameter = strtoupper($sig);
        $date = date('Y-m-d');
        $date = '2013-12-26';
        $url = "https://app.cloopen.com:8883/{$date}/Accounts/{$accountSid}/SMS/GetArrived?sig={$SigParameter}";
        $params = array(
            'appId'   => '8aaf0708773733a801775c8e437e0e88', //应用Id
            'smsType' => 0, //0:上行短信数据 1:短信状态报告 缺省1
            'count'    => 100, //查询状态的数量。最大500，缺省100
        );
        $paramstring = json_encode($params);
        $sttlen = strlen($paramstring);
        $options = [
            CURLOPT_ACCEPT_ENCODING => 'gzip,deflate',
            CURLOPT_HTTPHEADER => [
                //"Content-Length:{$sttlen};",
                'Accept:application/json;',
                'Content-Type:application/json;charset=utf-8;',
                "Authorization:{$base64}"
            ]
        ];
        $msgInfo = HttpUtils::post($url, $paramstring, $options);
        if (!$msgInfo['success']) {
            return EsUtils::stdMessage(false, '短信接口请求错误：' . $msgInfo['msg']);
        }
        $smsInfo = json_decode($msgInfo['data'], true); // array ('reason'=>'error key','result'=>NULL,'error_code'=>10001,)
        if ($smsInfo['statusCode'] != '000000') {
            return EsUtils::stdMessage(false, '短信接口请求错误：' . $smsInfo['statusCode']);
        }
        //返回用户上发验证码
        $code = '';
        foreach ($smsInfo['reports'] as $val) {
            if ($val['fromNum'] == $mobile) {
                $code = $val['content'];
                break;
            }
        }
        return $code;
    }
}
